package com.gec.wiki.controller;

import com.gec.wiki.pojo.Ebook;
import com.gec.wiki.pojo.req.EbookQueryReq;
import com.gec.wiki.pojo.req.EbookSaveReq;
import com.gec.wiki.pojo.resp.CommonResp;
import com.gec.wiki.pojo.resp.EbookResp;
import com.gec.wiki.pojo.resp.PageResp;
import com.gec.wiki.service.EbookService;
import com.gec.wiki.utils.CopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/ebook")
public class EbookController {



    @Autowired
    private EbookService ebookService;

    @GetMapping("/getEbookByEbookReq")
    public CommonResp getEbookByEbookReq(EbookQueryReq req){
        List<EbookResp> ebookResps = ebookService.getEbookByEbookReq(req);
        CommonResp<List<EbookResp>> resp = new CommonResp<>();
        resp.setContent(ebookResps);
        return resp;
    }

    @GetMapping("/getEbookListByPage")
    public CommonResp getEbookListByPage(@Valid EbookQueryReq req){
        PageResp<EbookResp> pageResp = ebookService.getEbookListByPage(req);

        CommonResp<PageResp<EbookResp>> resp = new CommonResp<>();
        resp.setContent(pageResp);

        return resp;
    }

    @PostMapping("/save")
    public CommonResp save(@Valid @RequestBody EbookSaveReq req){
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        //下面这个方法会根据ebook对象有无id去分是保存还是修改，没有id就是 save 有id update
        ebookService.saveOrUpdate(ebook);
        CommonResp<Object> resp = new CommonResp<>();
        return  resp;
    }

    @GetMapping("/remove/{id}")
    public CommonResp remove(@PathVariable("id") Integer id){
        System.out.println("id = " + id);
        ebookService.removeById(id);
        CommonResp<Object> resp = new CommonResp<>();
        return resp;
    }

    @PostMapping("/uploadImage")
    public CommonResp uploadImage(@RequestParam(value = "file", required = false) MultipartFile file){
        //动态获取项目所在的根目录
        String path = System.getProperty("user.dir");
        System.out.println("path ============== " + path+"\\web\\public\\image\\");
        String imageName = ebookService.uploadImage(file, path+"\\web\\public\\image\\");
        CommonResp<Object> resp = new CommonResp<>();
        resp.setContent(imageName);
        return resp;
    }
}
